﻿using System.Collections.Generic;

namespace Manoso.Data.FluentMap
{
    internal interface IJoinSelect
    {
        /// <summary>
        /// Starting from table name.
        /// </summary>
        string FromTable { get; set; }

        /// <summary>
        /// Starting from table alias.
        /// </summary>
        string FromAlias { get; set; }

        /// <summary>
        /// The where clause.
        /// </summary>
        string Where { get; set; }

        /// <summary>
        /// Id collections of tables, table alias is the key. 
        /// </summary>
        IDictionary<string, IList<IMapProperty>> Ids { get; }

        /// <summary>
        /// Property collections of tables, table alias is the key. 
        /// </summary>
        IDictionary<string, IList<IMapProperty>> Properties { get; }

        /// <summary>
        /// Collection of the joins.
        /// </summary>
        IList<IMapJoin> Joins { get; }

        /// <summary>
        /// Return a copy of the current JoinSelect instance.
        /// </summary>
        IJoinSelect Copy { get; }
    }

    internal class JoinSelect : IJoinSelect
    {
        public string FromTable { get; set; }
        public string FromAlias { get; set; }
        public string Where { get; set; }
        public IDictionary<string, IList<IMapProperty>> Ids { get; private set; }
        public IDictionary<string, IList<IMapProperty>> Properties { get; private set; }
        public IList<IMapJoin> Joins { get; private set; }

        public IJoinSelect Copy
        {
            get
            {
                var copy = new JoinSelect
                {
                    Ids = new Dictionary<string, IList<IMapProperty>>(),
                    FromTable = FromTable,
                    FromAlias = FromAlias,
                    Where = Where,
                };
                if (Properties == null)
                {
                    copy.Properties = new Dictionary<string, IList<IMapProperty>>();
                }
                else
                {
                    copy.Properties = Properties;
                    Properties = null;
                }
                foreach (var id in Ids)
                {
                    copy.Ids.Add(id.Key, id.Value);
                    if(copy.Properties.Count <= 0)
                        copy.Properties.Add(id.Key, id.Value);
                }
                copy.Joins.AddMany(Joins);
                return copy;
            }
        }

        internal JoinSelect()
        {
            Ids = new Dictionary<string, IList<IMapProperty>>();
            Properties = new Dictionary<string, IList<IMapProperty>>();
            Joins = new List<IMapJoin>();
        }
    }
}